package service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class ExternalClassloader extends ClassLoader {

    private final Path classPath;

    public ExternalClassloader(Path classPath) {
        this.classPath = classPath;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            String className=name.substring(name.lastIndexOf(".")+1);
            Path classFilePath = classPath.resolve(className + ".class");
            if (!Files.exists(classFilePath)) {
                throw new ClassNotFoundException("Class file not found: " + classFilePath);
            }

            byte[] classData = Files.readAllBytes(classFilePath);
            return defineClass(name, classData, 0, classData.length);
        } catch (IOException e) {
            System.err.println("Could not load class: " + name+e.getMessage());
            return null;
        }
    }
}
